using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;

namespace cb0tServer
{
    class FileFilters
    {
        private static Mutex mutex = new Mutex();
        private static List<FilterItem> items = new List<FilterItem>();

        private static List<String> type1 = new List<String>(new String[]
        {
            "kill",
            "ban",
        });

        private static List<String> type2 = new List<String>(new String[]
        {
            "pm",
            "announce",
            "clone"
        });

        public static void AddFileFilter(FilterItem item)
        {
            foreach (FilterItem f in items)
            {
                if (f.trigger == item.trigger && f.type == item.type)
                {
                    f.args = item.args;
                    SaveFilters();
                    return;
                }
            }

            items.Add(item);
            SaveFilters();
            return;
        }

        public static String RemoveFileFilter(ushort _id)
        {
            if (_id < items.Count)
            {
                String str = items[_id].trigger;
                items.RemoveAt(_id);
                SaveFilters();
                return str;
            }

            return null;
        }

        public static FilterItem[] GetFilters()
        {
            if (items.Count > 0)
            {
                return items.ToArray();
            }

            return null;
        }

        public static FilterItem Eval(String text)
        {
            int i = text.IndexOf(", ");
            if (i == -1) return null;
            FilterItem f = new FilterItem();
            f.trigger = text.Substring(0, i);
            if (f.trigger.Length < 1) return null;
            text = text.Substring(i + 2);
            i = text.IndexOf(", ");

            if (i == -1) // no args
            {
                f.type = text;
                if (f.type.Length < 1) return null;
                f.args = null;
                if (type1.Contains(f.type)) return f;
                return null;
            }
            else // args
            {
                f.type = text.Substring(0, i);
                if (f.type.Length < 1) return null;
                text = text.Substring(i + 2);
                f.args = text;
                if (f.args.Length < 1) return null;
                if (type2.Contains(f.type)) return f;
                return null;
            }
        }

        public static void LoadFilters()
        {
            items.Clear();

            if (!File.Exists(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/filefilters.xml")) return;

            try
            {
                FileStream f = new FileStream(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/filefilters.xml", FileMode.Open);
                XmlReader xml = XmlReader.Create(new StreamReader(f));

                xml.MoveToContent();
                xml.ReadSubtree().ReadToFollowing("filefilters");

                while (xml.ReadToFollowing("filefilter"))
                {
                    FilterItem a = new FilterItem();

                    xml.ReadSubtree().ReadToFollowing("trigger");
                    a.trigger = Encoding.UTF8.GetString(Convert.FromBase64String(xml.ReadElementContentAsString()));
                    xml.ReadToFollowing("type");
                    a.type = Encoding.UTF8.GetString(Convert.FromBase64String(xml.ReadElementContentAsString()));
                    xml.ReadToFollowing("args");
                    a.args = xml.ReadElementContentAsString();
                    if (a.args != "") a.args = Encoding.UTF8.GetString(Convert.FromBase64String(a.args));

                    items.Add(a);
                }

                xml.Close();
                f.Flush();
                f.Close();
            }
            catch { }
        }

        private static void SaveFilters()
        {
            mutex.WaitOne();

            try
            {
                XmlWriterSettings appearance = new XmlWriterSettings();
                appearance.Indent = true;
                XmlWriter xml = XmlWriter.Create(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/filefilters.xml", appearance);

                xml.WriteStartDocument();
                xml.WriteStartElement("filefilters");

                foreach (FilterItem a in items)
                {
                    xml.WriteStartElement("filefilter");
                    xml.WriteElementString("trigger", Convert.ToBase64String(Encoding.UTF8.GetBytes(a.trigger)));
                    xml.WriteElementString("type", Convert.ToBase64String(Encoding.UTF8.GetBytes(a.type)));
                    xml.WriteElementString("args", a.args == null ? "" : Convert.ToBase64String(Encoding.UTF8.GetBytes(a.args)));
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Flush();
                xml.Close();
            }
            catch { }

            mutex.ReleaseMutex();
        }

    }
}
